<?php

namespace app\admin\controller\mall;

use app\api\model\mysql\MallOrder;
use app\api\model\mysql\MallOrderGoods;
use app\api\model\mysql\MallOrderRefund;
use app\api\model\mysql\MallUser;
use app\api\model\mysql\MallUserPaylog;
use app\common\controller\AdminController;
use app\common\lib\ArrClass;
use app\common\lib\Str;
use think\App;

class Service extends AdminController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new MallOrderRefund();
    }

    public function index(){
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();
            $count = $this->model
                ->where($where)
                ->count();
            $list = $this->model
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();

            foreach ($list as $k=>$v){
                $order =(new MallOrder())->getByOrderIds($v['order_id']);
                if($order){
                    $list[$k]['ordersn']=$order['ordersn'];
                    $list[$k]['paytype']=$order['paytype'];
                }
                if($v['refund_time']){
                    $list[$k]['refund_time'] =date('Y-m-d H:i:s',$v['refund_time']);
                }else{
                    $list[$k]['refund_time'] ='--';
                }

            }
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }

    /**
     * 处理售后
     * @param $id
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit($id){
        $row = $this->model->find($id);
        $orderinfo =(new MallOrder())->where("id='".$row['order_id']."'")->find();
        empty($row) && $this->error('数据不存在');
        if ($this->request->isPost()) {
            $post = $this->request->post();
            if($post['realrefund_money']>$orderinfo['payprice']){
                $this->error('退款金额不能大于实际支付金额');
            }

            try {
                // 退款流程
                if($orderinfo['paytype']==1){
                    $refundno =Str::RandomStr();
                    $objClass = ArrClass::payAttr();
                    $obj = ArrClass::initClass('wx', $objClass, [], true);
                    $payprice =intval($orderinfo['payprice']*100);
                    $refundprice =intval($post['realrefund_money']*100);
                    // 商城支付记录
                    $paylog = (new MallUserPaylog())->getUserPaylogByOpenid($orderinfo['openid'],$orderinfo['id']);
                    if(!$paylog || ($paylog && $paylog['status']!=1)){
                        $this->model->rollback();
                        $this->error('退款失败');
                    }
                    $result= $obj->refund($paylog['ordersn'],$refundno,$payprice,$refundprice,['refund_desc'=>'共享商城支付退款']);
                    if($result['return_code'] == 'SUCCESS'){
                        if($result['result_code'] =='SUCCESS'){
                            $orderinfo->save(array('orderstatus'=>4,'isrefund'=>1,'refundtime'=>time()));
                            $row->save(array('status'=>1,'refund_time'=>time(),'realrefund_money'=>$post['realrefund_money']));
                        }else{

                            $this->error('退款失败');
                        }
                    }else{

                        $this->error('退款失败');
                    }
                }
            } catch (\Exception $e) {

                $this->error($e->getMessage());
            }

            $this->success('退款成功');
        }
        switch ($row['orderstatus']){
            case 0:
                $row['statusname'] ='待付款';
                break;
            case 1:
                $row['statusname'] ='待发货';
                break;
            case 2:
                $row['statusname'] ='待收货';
                break;
            case 3:
                $row['statusname'] ='已完成';
                break;
            case 4:
                $row['statusname'] ='售后/退款';
                break;
            default:
                $row['statusname'] ='已取消';
                break;
        }
        $userinfo =(new MallUser())->getUserByList($row['openid'],'id,openid,nickName');
        $row['nickName'] =$userinfo['nickName'];
        $goodslist=(new MallOrderGoods())->getByOrderGoodsList($row['order_id']);
        if($row['refund_imgs']){
            $refundimgs =json_decode($row['refund_imgs'],true);
            $row['refund_imgs'] =$refundimgs;
        }else{
            $row['refund_imgs']=[];
        }
        if($row['refund_time']){
            $row['refund_time'] =date('Y-m-d H:i:s',$row['refund_time']);
        }
        $this->assign('row', $row);
        $this->assign('orderinfo', $orderinfo);
        $this->assign('goodslist', $goodslist);
        return $this->fetch();
    }

}